﻿using System.Collections.Concurrent;
using System.Collections.Generic;

namespace Fetches.Fetch.Factory.Persistence
{
    /// <summary>
    ///     调度信息
    /// </summary>
    public class UnitSchedules
    {
        /// <summary>
        ///     Factory Unit ID
        /// </summary>
        public long Id { get; }

        /// <summary>
        /// 操作端点是能被动操作的Factory才有的
        /// </summary>
        public string Endpoint { get; set; }


        /// <summary>
        ///     分配到的Fetcher列表,以FetcherType分组
        /// </summary>
        public ConcurrentDictionary<string, ISet<long>> DispatchedFetchers { get; set; }
            = new ConcurrentDictionary<string, ISet<long>>();

        /// <summary>
        /// 支持的Fetcher类型
        /// </summary>
        public IEnumerable<string> SupportedFetcherTypes { get; set; }

        public UnitSchedules(long id)
        {
            Id = id;
        }


        #region 任务相关方法

        /// <summary>
        /// 分配Fetcher，不要让外部方法依赖DispatchedFetchers的数据结构
        /// </summary>
        /// <param name="fetcherType"></param>
        /// <param name="fetcherId"></param>
        public void DispatchFetcher(long fetcherId, string fetcherType)
        {
            lock (DispatchedFetchers)
            {
                if (!DispatchedFetchers.TryGetValue(fetcherType, out var fetchers))
                {
                    fetchers = new HashSet<long>();
                    DispatchedFetchers.TryAdd(fetcherType, fetchers);
                }

                fetchers.Add(fetcherId);
            }

        }

        /// <summary>
        /// 移除已分配的fetcher
        /// </summary>
        /// <param name="fetcherType"></param>
        /// <param name="fetcherId">fetcherID</param>
        public void DismissFetcher(long fetcherId, string fetcherType)
        {
            lock (DispatchedFetchers)
            {
                if (DispatchedFetchers.TryGetValue(fetcherType, out var fetchers))
                {
                    fetchers.Remove(fetcherId);
                }
            }
        }

        #endregion

    }
}